#pragma once
#include<iostream>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<cstdlib>
#include<unistd.h>
#include<string.h>

using namespace std;

const char*pathname="/home/lsh";
int proj_id=0x66;
const int defaultsize=4096;//单位是字节

string ToHex(key_t key)
{
    char buffer[1024];
    snprintf(buffer,sizeof(buffer),"%x",key);
    return string("0x")+buffer;
}

key_t GetKeyOrDie()
{
    key_t key=ftok(pathname,proj_id);
    if(key==-1)
    {
        perror("ftok");
        exit(-1);
    }
    return key;
}

int GetSharedMemoryOrDie(key_t key,size_t size,int flag)
{
    int ret=shmget(key,size,flag);
    if(ret==-1)
    {
        perror("shmget");
        exit(-1);
    }
    return ret;
}

//一个进程创建共享内存
int CreateSharedMemory(key_t key,size_t size)
{
    return GetSharedMemoryOrDie(key,size,IPC_CREAT|IPC_EXCL|0666);
}
//另一个进程获取共享内存
int GetSharedMemory(key_t key,size_t size)
{
    return GetSharedMemoryOrDie(key,size,IPC_CREAT);
}

//删除共享内存
void DeletingSharedMemory(int shmid)
{
    int ret=shmctl(shmid,IPC_RMID,NULL);
    if(ret==-1)
    {
        perror("shmtl");
    }
    else
    {
        cout<<"Deleting the shared memory succeeded"<<endl;
    }
}

void DeBug(int shmid)
{
    struct shmid_ds shmds;
    int ret=shmctl(shmid,IPC_STAT,&shmds);
    if(ret==-1)
    {
        perror("shmctl");
    }
    else
    {
        cout<<"shmds.shm_segsz:"<<shmds.shm_segsz<<endl;//大小
        cout<<"shmds.shm_nattch:"<<shmds.shm_nattch<<endl;//当前挂接进程的个数
        cout<<"shmds.shm_ctime:"<<shmds.shm_ctime<<endl;//挂接的时间
        cout<<"shmds.shm_perm.__key:"<<ToHex(shmds.shm_perm.__key)<<endl;
    }
}

//挂接上共享内存
void* AttachSharedMemory(int shmid)
{
    void* addr=shmat(shmid,nullptr,0);
    if((long long)addr==-1)
    {
        perror("shmat");
        return 0;
    }
    return addr;
}

//和共享内存取消关联
int DetachShareMemory(const void*addr)
{
    int ret=shmdt(addr);
    if(ret==-1)
    {
        perror("shmdt");
        return -1;
    }
    return ret;
}